<template>
  <div class="info_entry">
    <div class="container">
      <div class="row">
        <label class="lab">姓名</label>
        <div class="inp">
          <input type="text" placeholder="请输入姓名" v-model="userInfo.name" maxlength="18" />
        </div>
      </div>
      <div class="row">
        <label class="lab">民族</label>
        <div class="inp">
          <input type="text" placeholder="请输入民族" v-model="userInfo.nationName" maxlength="18" />
        </div>
      </div>
      <div class="row">
        <label class="lab">身份证号</label>
        <div class="inp">
          <input type="text" placeholder="请输入身份证号" v-model="userInfo.cardNo" maxlength="18" />
        </div>
      </div>
      <div class="row">
        <label class="lab">户籍地址</label>
        <div class="inp">
          <input type="text" placeholder="请输入户籍地址" v-model="userInfo.address" maxlength="18" />
        </div>
      </div>
      <div class="row">
        <label class="lab">手机号码</label>
        <div class="inp">
          <input type="number" placeholder="请输入手机号码" v-model="userInfo.phone" oninput="if(value.length > 11)value = value.slice(0, 11)" />
        </div>
      </div>
      <div class="row">
        <label class="lab">验证码</label>
        <div class="inp">
          <input type="text" placeholder="请输入验证码" @blur.prevent="inputLoseFocus" v-model="code" maxlength="6" />
        </div>
        <span class="code" @click="getSmsCode">{{ codeBtnText }}</span>
      </div>
    </div>
    <div class="btn" @click="submitFn">确定</div>

    <div class="logo" v-show="hidshow">
      <img src="@/libs/images/dibu.png" />
      <p>重庆公安旅业人证比对系统</p>
    </div>

    <div class="mask" v-if="show">
      <div class="content">
        <div class="money">服务费：<span>{{ info.chargeAmount || info.payAmount }}</span>元</div>
        <div class="tip">请确认个人身份信息</div>
        <div class="user">
          <p>姓名：{{ userInfo.name }}</p>
          <p>民族：{{ userInfo.nationName }}</p>
          <p>身份证号：{{ userInfo.cardNo }}</p>
          <p>户籍地址：{{ userInfo.address }}</p>
        </div>
        <button class="btn-c cancel" @click.stop="show = false">信息错误，重新填写</button>
        <button class="btn-c confirm" @click.stop="confirmFn">信息正确，确认支付</button>
      </div>
    </div>
  </div>
</template>

<script>
import wx from "weixin-js-sdk";
import { paramsValidate,phoneNumValidate,idCardValidate } from "@/libs/js/validate.js";
export default {
  name: "InfoEntry",
  data() {
    return {
      wxCode: "",
      info: {
        chargeAmount: 5
      },
      typeCode: "face_10001", // 短信模板
      code: "", // 验证码
      userInfo: {
        name: "",
        nationName: "",
        cardNo: "",
        address: "",
        phone: "",
        optSn: ""
      },
      paramsName: [
        { key: "name", tip: "姓名" },
        { key: "nation", tip: "民族" },
        { key: "cardNo", tip: "身份证号" },
        { key: "address", tip: "户籍地址" },
        { key: "phone", tip: "手机号码" },
        { key: "optSn", tip: "操作编号" }
      ],
      codeBtnText: "获取验证码",
      timer: null, // 验证码倒计时
      cutdown: 60, // 验证码倒计时
      isSend: true,
      show: false,
      hidshow: true // 显示或者隐藏底部logo
    };
  },
  watch: {
    "userInfo.cardNo": function(val) {
      this.userInfo.cardNo = val.toUpperCase();
    }
  },
  methods: {
    // 解决调起手机软键盘页面被顶到底部再关闭软键盘页面底部留白的问题
    inputLoseFocus() {
      setTimeout(() => {
        window.scrollTo(0, 0);
      }, 100);
    },
    // 判断是否可访问
    getGuestExist() {
      let uId = sessionStorage.getItem("id");
      this.$api.system
        .queryGuestExist(this.userInfo.optSn, uId)
        .then(res => {
          if (res) {
            this.getInfo();
            // this.getSmsTemplate();
          } else {
            this.$router.push({ path: "/errors", query: { type: 1 } });
          }
        })
        .catch(err => {
          this.$router.push({ path: "/errors", query: { type: 2 } });
        });
    },
    // 获取录入信息
    getInfo() {
      this.$api.system
        .queryGuestRegister(this.userInfo.optSn)
        .then(res => {
          console.log(res, "getInfo");
          if (res) {
            this.info = res;
            this.userInfo.name = res.name;
            this.userInfo.nationName = res.nationName;
            this.userInfo.cardNo = res.cardNo;
            this.userInfo.address = res.address;
            this.userInfo.phone = res.phone;
            if (res.payStatus != 1 && res.paySn) {
              this.show = true;
            }
            if (res.payStatus == 1) {
              this.$router.push({ path: "/success" });
            }
          }
        })
        .catch(err => {});
    },
    // 获取短信模板
    getSmsTemplate() {
      this.$api.system
        .querySmsTemplateList("tangor_ebook")
        .then(res => {
          this.typeCode = res[0].typeCode;
        })
        .catch(err => {});
    },
    // 获取验证码
    getSmsCode() {
      if (!this.isSend) {
        return false;
      }
      if (!this.userInfo.phone) {
        this.common.$emit("tips", {
          show: true,
          content: "手机号码不能为空！"
        });
        return false;
      }
      if (!phoneNumValidate(this.userInfo.phone)) {
        this.common.$emit("tips", {
          show: true,
          content: "手机号码输入有误！"
        });
        return false;
      }
      // if (!this.typeCode) {
      //   this.getSmsTemplate();
      // }
      let data = {
        phone: this.userInfo.phone,
        typeCode: this.typeCode
      };
      console.log(data, "getSmsCode");
      this.$api.system
        .sendSmsCode(data)
        .then(res => {
          console.log(res, "getSmsCode");
          this.isSend = false;
          this.codeCountdown();
        })
        .catch(err => {});
    },
    // 获取验证码倒计时
    codeCountdown() {
      if (this.timer === null) {
        let cutdown = this.cutdown;
        this.timer = setInterval(() => {
          --cutdown;
          this.codeBtnText = cutdown + "s";
          this.isSend = false;
          if (cutdown < 1) {
            this.codeBtnText = "获取验证码";
            this.isSend = true;
            clearInterval(this.timer);
            this.cutdown = 60;
            this.timer = null;
          }
        }, 1000);
      }
    },
    // 信息提交
    submitFn() {
      let empty = paramsValidate(this.userInfo, this.paramsName);
      if (empty) {
        this.common.$emit("tips", {
          show: true,
          content: empty + "不能为空！"
        });
        return false;
      }
      if (!this.code) {
        this.common.$emit("tips", {
          show: true,
          content: "验证码不能为空！"
        });
        return false;
      }
      if (!idCardValidate(this.userInfo.cardNo)) {
        this.common.$emit("tips", {
          show: true,
          content: "身份证号输入有误！"
        });
        return false;
      }
      if (this.userInfo.cardNo.indexOf("x") > -1) {
        this.userInfo.cardNo.replace(/^\x/, "X");
      }
      let data = {
        code: this.code,
        phone: this.userInfo.phone,
        typeCode: this.typeCode
      };
      this.common.$emit("loading", true);
      this.$api.system
        .verifyCode(data)
        .then(res => {
          console.log(res, "submit");
          this.$api.system
            .createGuestRegister(this.userInfo)
            .then(res => {
              console.log(res, "submit");
              this.info = res;
              this.common.$emit("loading", false);
              if (res.isPay === 1) {
                this.show = res.isPay === 1;
              } else {
                this.$router.push({ path: "/success" });
              }
            })
            .catch(err => {
              this.common.$emit("loading", false);
            });
        })
        .catch(err => {
          this.common.$emit("loading", false);
        });
    },
    // 获取url地址参数
    getUrlParam(name) {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      let r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    // 确认支付
    confirmFn() {
      let that = this;
      let id = sessionStorage.getItem("id");
      let data = {
        paySn: that.info.paySn,
        openId: id
      };
      that.common.$emit("loading", true);
      that.$api.system
        .postPayParam(data)
        .then(res => {
          console.log(res, "confirmFn");
          that.show = false;
          that.weixinPay(res);
        })
        .catch(err => {
          that.show = true;
          that.common.$emit("loading", false);
        });
    },
    // 微信支付
    weixinPay(wxConfig) {
      let that = this;
      that.common.$emit("loading", false);
      that.$api.system
        .getJsApiTicketConfig(window.location.href)
        .then(res => {
          console.log(res, "weixinPay");
          wx.config({
            // beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来
            appId: res.appId, // 必填，企业微信的corpID
            timestamp: res.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.nonceStr, // 必填，生成签名的随机串 必填，生成签名的随机串
            signature: res.signature, // 必填，签名
            jsApiList: ["chooseWXPay"] // 要调用的微信接口,所有要调用的API都要加到这个列表中
          });
          wx.ready(function() {
            wx.chooseWXPay({
              timestamp: wxConfig.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: wxConfig.nonceStr, // 支付签名随机串，不长于 32 位
              package: wxConfig.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
              signType: wxConfig.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: wxConfig.sign, // 支付签名
              success: function (res) {
                console.log(res);
                that.$router.push({ path: "/success" });
              },
              cancel: function (res) {
                that.show = true;
                that.common.$emit("tips", {
                  show: true,
                  content: "已取消支付"
                });
              },
              fail: function (res) {
                that.show = true;
                that.common.$emit("tips", {
                  show: true,
                  content: "支付失败，请重新支付"
                });
              }
            });
          });
        })
        .catch(err => {});
    },
  },
  created() {
    let _this = this;
    _this.userInfo.optSn = _this.$route.query.optSn;
    if (_this.$route.query.optSn) {
      _this.init(function() {
        _this.getGuestExist();
      });
    } else {
      _this.$router.push({ path: "/errors", query: { type: 2 } });
    }
  },
  mounted() {
    const ua = window.navigator.userAgent;
    if (ua.indexOf("Android") > -1 || ua.indexOf("iPhone") > -1) {
      const docmHeight = document.body.clientHeight; // 默认屏幕高度
      window.onresize = () => {
        var nowHeight = document.body.clientHeight; // 实时屏幕高度
        if (docmHeight !== nowHeight) {
          this.hidshow = false;
        } else {
          this.hidshow = true;
        }
      };
    }
  }
};
</script>

<style lang="less" scoped>
.info_entry {
  background: #FBFBFB;
  height: 100vh;
  .container {
    background: #fff;
    padding: 0 20px;
    overflow: hidden;
    .row {
      display: -webkit-flex; /* 新版本语法: Chrome 21+ */
      display: flex; /* 新版本语法: Opera 12.1, Firefox 22+ */
      display: -webkit-box; /* 老版本语法: Safari, iOS, Android browser, older WebKit browsers. */
      display: -moz-box; /* 老版本语法: Firefox (buggy) */
      display: -ms-flexbox; /* 混合版本语法: IE 10 */
      height: 60px;
      font-size: 15px;
      border-bottom: 1px solid #E4E4EE;
      .lab {
        display: block;
        width: 80px;
        line-height: 60px;
        color: #999;
        margin-right: 30px;
      }
      .inp {
        -webkit-flex: 1; /* Chrome */
        -ms-flex: 1; /* IE 10 */
        flex: 1; /* NEW, Spec - Opera 12.1, Firefox 20+ */
        -webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
        -moz-box-flex: 1; /* OLD - Firefox 19- */
        line-height: 60px;
        padding-right: 20px;
        input {
          width: 100%;
          font-size: 15px;
        }
      }
      .code {
        display: inline-block;
        padding: 3px 5px;
        margin: 17px 0;
        min-width: 72px;
        text-align: center;
        font-size: 12px;
        color: #ff6600;
        border: 1px solid #ff6600;
        border-radius: 50px;
      }
    }
  }
  .btn {
    background: #FF6600;
    margin: 32px 20px 0;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-weight: 400;
    font-size: 16px;
    color: #fff;
    border-radius: 3px;
  }
  .mask {
    position: relative;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 100;
    .content {
      width: 80%;
      min-width: 250px;
      padding: 0 21px 7px;
      background: #fff;
      border-radius: 5px;
      text-align: center;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      .money {
        padding-top: 26px;
        margin-bottom: 5px;
        font-weight: 700;
        font-size: 15px;
        color: #333;
      }
      .tip {
        font-size: 14px;
        color: #666;
      }
      .user {
        padding: 18px 0;
        text-align: left;
        p {
          line-height: 25px;
          font-size: 12px;
          color: #666
        }
      }
      .btn-c {
        outline: none;
        background: #fff;
        border: 1px solid #ff6600;
        margin-bottom: 15px;
        width: 85%;
        height: 40px;
        line-height: 40px;
        font-size: 13px;
        border-radius: 5px;
        color: #ff6600;
        &.confirm {
          background: #ff6600;
          color: #fff;
        }
      }
    }
  }
}
</style>